import { UserModule } from './store/user'
import { Route, NavigationGuardNext } from 'vue-router'
import router, { constantRoutes } from '@/router/index'
const whiteList = ['/login', '/404', '/auth-redirect']

router.beforeEach(async(to: Route, _: Route, next: NavigationGuardNext) => {
  // Start progress bar

  // Determine whether the user has logged in  UserModule.token
  if (true) {
    if (to.path === '/login') {
      // If is logged in, redirect to the home page
      next({ path: '/' })
    } else {
      // Check whether the user has obtained his permission roles
      if (UserModule.roles.length !== 0) {
        try {
          // Note: roles must be a object array! such as: ['admin'] or ['developer', 'editor']
          // await UserModule.GetUserInfo()
          const roles = UserModule.roles
          // Generate accessible routes map based on role
          // PermissionModule.GenerateRoutes(roles)
          // Dynamically add accessible routes
          // router.addRoutes(PermissionModule.dynamicRoutes)
          router.addRoutes(constantRoutes)
          // Hack: ensure addRoutes is complete
          // Set the replace: true, so the navigation will not leave a history record
          next({
            path: to.path,
            hash: to.hash,
            query: to.query,
            params: to.params,
            replace: true
          })
        } catch (err) {
          console.log(err)

          // Remove token and redirect to login page
          UserModule.ResetToken()
          next(`/login?redirect=${to.path}`)
        }
      } else {
        next()
      }
    }
  } else {
    // Has no token
    if (whiteList.indexOf(to.path) !== -1) {
      // In the free login whitelist, go directly
      next()
    } else {
      // Other pages that do not have permission to access are redirected to the login page.
      next('/404')
    }
  }
})

router.afterEach((to: Route) => {
  // Finish progress bar
  // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939

  // set page title
  document.title = to.meta.title
})
